package de.luisoft.web.servlet;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;

import de.luisoft.dao.MyDAO;
import de.luisoft.dto.WahlDTO;
import de.luisoft.ui.model.ProjectModel;
import de.luisoft.ui.model.ProjectModelContainer;

public abstract class AbstractListServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(AbstractListServlet.class.getName());

	
	final protected Map<String, List<WahlDTO>> getVotesByProject(
			Map<String, ProjectModel> projectbyName) {

		Map<String, List<WahlDTO>> map = new LinkedHashMap<String, List<WahlDTO>>();

		MyDAO my = new MyDAO();
		List<WahlDTO> wahllist = my.getAllVerified(true);
		ProjectModelContainer cont = new ProjectModelContainer();
		List<ProjectModel> projects = cont.getList();

		for (WahlDTO w: wahllist) {
			log.fine("w=" + w + ": " + w.getSelect());
		}

		for (ProjectModel p : projects) projectbyName.put(p.getName(), p);
		for (ProjectModel p : projects) map.put(p.getName(), new ArrayList<WahlDTO>());

		return getVotesByProject(projectbyName, map, wahllist);
	}		
		
	final Map<String, List<WahlDTO>> getVotesByProject(
			Map<String, ProjectModel> projectbyName,
			Map<String, List<WahlDTO>> map,
			List<WahlDTO> wahllist) {


		List<WahlDTO> notAssigned = new ArrayList<WahlDTO>();
		while (!wahllist.isEmpty()) {
			for (ListIterator<WahlDTO> wIt = wahllist.listIterator() ; wIt.hasNext(); ) {
				WahlDTO w = wIt.next(); 
				log.fine("handle " + w.getName() + ";" + w.getSelect());
				List<String> ps = w.getSelect();
				String firstVote = ps.get(0);
				log.fine("firstVote=" + firstVote);

				int cap = projectbyName.get(firstVote).getCapacity();

				int voteCount = map.get(firstVote).size();
				log.fine("cap=" + cap + "/voteCount=" + voteCount);
				if (cap > voteCount) {
					// add to map
					map.get(firstVote).add(w);
					// remove w from wahlist
					wIt.remove();
				} else {
					// project has no capacity, so remove vote 
					ps.remove(0);
					if (ps.isEmpty()) {
						notAssigned.add(w);
						wIt.remove();
					}
				}
				if (!notAssigned.isEmpty()) log.fine("notAssigned=" + notAssigned);
				log.fine("map=" + map + "\n");
			}
		}
		
		log.info("return map=" + map.size());
		return map;
	}
}
